import 'package:flutter/material.dart';
import 'package:smart_shoes/define/define_colors.dart';
import 'package:smart_shoes/tools/String_tool.dart';
import 'package:table_calendar/table_calendar.dart';

class WidgetTools {
  Widget TextTitle(String title) {
    return Text(
      title,
      style: TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.bold,
        color: CustomColors.textColor,
      ),
    );
  }

  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  MaterialButton createMaterialButton(
    double buttonWidth,
    String title,
    Color bgColor,
    Color textColor,
    double borderWidth,
    buttonAction, {
    double radius = 0,
  }) {
    // 边框样式
    RoundedRectangleBorder shape = RoundedRectangleBorder(
      side: BorderSide(
        width: borderWidth,
        color: borderWidth == 0 ? Colors.white : Colors.blue,
      ),
      borderRadius: BorderRadius.all(Radius.circular(radius)),
    );

    Text textWidget = Text(
      title,
      style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
    );
    //生成按钮
    return MaterialButton(
      color: bgColor,
      textColor: textColor,
      minWidth: buttonWidth,
      height: 49,
      shape: shape,
      onPressed: () {
        if (buttonAction != null) {
          buttonAction!();
        }
      },
      child: textWidget,
    );
  }

  // *
  /// -  @description: 自定义按钮
  /// -  @Date: 2022-06-30 15:49
  /// -  @parm: buttonWidth 按钮宽度
  ///           title 按钮标题
  ///           buttonAction 点击方法
  ///           bgColor颜色
  ///           textColor 字体颜色
  ///           borderWidth 边框宽度
  ///           borderColor 边框颜色
  ///           radius圆角
  ///           fontSize 字体大小
  ///           fontWeight 加粗
  ///           height 按钮高度
  /// -  @return {*}
  ///
  Widget createCustomInkWellButton(
    String title,
    buttonAction, {
    double? buttonWidth,
    Color? bgColor,
    Color? textColor,
    double borderWidth = 0.0,
    Color? borderColor,
    double radius = 0.0,
    double fontSize = 15,
    FontWeight? fontWeight,
    double height = 49,
    BoxShadow? shadow,
    Image? leftImage,
  }) {
    // 边框样式
    // RoundedRectangleBorder shape = RoundedRectangleBorder(
    //   side: BorderSide(width: borderWidth, color: borderColor ?? Colors.white),
    //   borderRadius: BorderRadius.all(Radius.circular(radius)),
    // );

    Text textWidget = Text(
      title,
      style: TextStyle(
        fontSize: fontSize,
        fontWeight: fontWeight,
        color: textColor,
      ),
      textAlign: TextAlign.center,
      // maxLines: 1,
    );

    Widget lView;
    if (leftImage != null) {
      lView = leftImage;
    } else {
      lView = const SizedBox();
    }
    //生成按钮
    return Container(
      width: buttonWidth,
      height: height,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 5, right: 5),
      decoration: BoxDecoration(
        color: bgColor,
        // Move the borderRadius parameter out of Border.all
        border: Border.all(
          width: borderWidth,
          color: borderColor ?? Colors.transparent,
        ),
        borderRadius: BorderRadius.all(Radius.circular(radius)),
        boxShadow: [
          shadow ??
              const BoxShadow(
                color: CustomColors.buttonColor,
                offset: Offset(0, 0),
                blurRadius: 6,
                spreadRadius: 2,
              ),
        ],
      ),
      child: InkWell(
        onTap: () {
          if (buttonAction != null) {
            buttonAction!();
          }
        },
        child: Row(children: [lView, Expanded(child: textWidget)]),
      ),
    );
  }

  /// *
  /// -  @description: 自定义按钮
  /// -  @Date: 2022-06-30 15:49
  /// -  @parm: buttonWidth 按钮宽度
  ///           title 按钮标题
  ///           buttonAction 点击方法
  ///           bgColor颜色
  ///           textColor 字体颜色
  ///           borderWidth 边框宽度
  ///           borderColor 边框颜色
  ///           radius圆角
  ///           fontSize 字体大小
  ///           fontWeight 加粗
  ///           height 按钮高度
  /// -  @return {*}
  ///
  Widget createCustomButton(
    double buttonWidth,
    String title,
    buttonAction, {
    Color? bgColor,
    Color? textColor,
    double borderWidth = 0.0,
    Color? borderColor,
    double radius = 0.0,
    double fontSize = 15,
    FontWeight? fontWeight,
    double height = 49,
    BoxShadow? shadow,
  }) {
    // 边框样式
    RoundedRectangleBorder shape = RoundedRectangleBorder(
      side: BorderSide(width: borderWidth, color: borderColor ?? Colors.white),
      borderRadius: BorderRadius.all(Radius.circular(radius)),
    );

    Text textWidget = Text(
      title,
      style: TextStyle(fontSize: fontSize, fontWeight: fontWeight),
      maxLines: 1,
    );
    //生成按钮
    return Container(
      width: buttonWidth,
      height: height,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(radius)),
        boxShadow: [
          shadow ??
              const BoxShadow(
                color: Colors.white,
                offset: Offset(0, 0),
                blurRadius: 6,
                spreadRadius: 2,
              ),
        ],
      ),
      child: MaterialButton(
        color: bgColor,
        textColor: textColor,
        shape: shape,
        onPressed: () {
          if (buttonAction != null) {
            buttonAction!();
          }
        },
        child: textWidget,
      ),
    );
  }

  Widget customAlertContent(
    BuildContext context,
    ValueChanged? buttonAction,
    GestureTapCallback? selectAction,
  ) {
    return Container(
      margin: EdgeInsets.only(left: 19.5, right: 19.5, top: 223),
      padding: EdgeInsets.all(16),
      height: 312,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            // mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(child: SizedBox(width: 10)),
              Text(
                "设置关闭条件",
                style: TextStyle(
                  color: CustomColors.textColor,
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Expanded(child: SizedBox(width: 10)),
              GestureDetector(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Image.asset(
                  "assets/images/guanbi.png",
                  width: 15,
                  height: 15,
                ),
              ),
            ],
          ),
          SizedBox(height: 20.5),
          //说明
          Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "当天关闭",
                    style: TextStyle(
                      color: CustomColors.textColor,
                      fontSize: 13,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 6.5),
                  Text(
                    "关闭当天的电子围栏，当天不在推送消息提示",
                    style: TextStyle(
                      color: CustomColors.grey,
                      fontSize: 11,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              SizedBox(width: 48),
              SizedBox(
                width: 36,
                height: 19,
                child: Card(
                  child: Switch(value: true, onChanged: (bool value) {}),
                ),
              ),
              //范围关闭(可选单个条件)
              // Text(
              //   "范围关闭(可选单个条件)",
              //   style: TextStyle(
              //     color: CustomColors.textColor,
              //     fontSize: 13,
              //     fontWeight: FontWeight.bold,
              //   ),
              // ),
            ],
          ),
          Text(
            "范围关闭(可选单个条件)",
            style: TextStyle(
              color: CustomColors.textColor,
              fontSize: 13,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 11.5),
          Row(
            children: [
              Text(
                "关闭所选时间段：",
                style: TextStyle(color: CustomColors.textColor, fontSize: 12),
              ),
              SizedBox(width: 4),
              Expanded(child: createEndTimePicker(context)),
            ],
          ),
          SizedBox(height: 21.5),
          Row(
            children: [
              Text(
                "关闭所选日期：",
                style: TextStyle(color: CustomColors.textColor, fontSize: 12),
              ),
              SizedBox(width: 16),
              Expanded(child: createDateTimePicker(context)),
              SizedBox(height: 22),
            ],
          ),
          SizedBox(height: 22),
          Material(
            child: createCustomInkWellButton(
              height: 34,
              "确定",
              textColor: Colors.white,
              () {
                Navigator.of(context).pop();
              },
              radius: 17,
              buttonWidth: 305.5,
              bgColor: CustomColors.buttonColor,
              shadow: BoxShadow(),
            ),
          ),
        ],
      ),
    );
  }

  /// 创建一个点击选择结束时间的组件
  Widget createEndTimePicker(
    BuildContext context, {
    Function(DateTime)? onTimeSelected,
  }) {
    return EndTimePickerWidget(
      context: context,
      onTimeSelected: onTimeSelected,
    );
  }

  Widget createDateTimePicker(
    BuildContext context, {
    Function(DateTime)? onTimeSelected,
  }) {
    return DatePickerWidget(context: context, onTimeSelected: onTimeSelected);
  }
}

class EndTimePickerWidget extends StatefulWidget {
  // 定义构造函数和属性
  final BuildContext context;
  final Function(DateTime)? onTimeSelected;

  const EndTimePickerWidget({
    Key? key,
    required this.context,
    this.onTimeSelected,
  }) : super(key: key);

  @override
  _EndTimePickerWidgetState createState() => _EndTimePickerWidgetState();
}

class _EndTimePickerWidgetState extends State<EndTimePickerWidget> {
  TimeOfDay? _selectedTime, _beginTime, _endTime;

  Future<void> SelectedendTime() async {
    // 选择时间
    final TimeOfDay? pickedTime = await showTimePicker(
      context: widget.context,
      initialTime: _selectedTime ?? TimeOfDay.now(),
    );

    if (pickedTime != null) {
      final DateTime time = DateTime(pickedTime.hour, pickedTime.minute);

      setState(() {
        _selectedTime = pickedTime;

        _endTime = pickedTime;
      });

      if (widget.onTimeSelected != null) {
        widget.onTimeSelected!(time);
      }
    }
  }

  Future<void> SelectedbeginTime() async {
    // 选择时间
    final TimeOfDay? pickedTime = await showTimePicker(
      context: widget.context,
      initialTime: _selectedTime ?? TimeOfDay.now(),
    );

    if (pickedTime != null) {
      final DateTime time = DateTime(pickedTime.hour, pickedTime.minute);

      setState(() {
        _selectedTime = pickedTime;
        _beginTime = pickedTime;
      });

      if (widget.onTimeSelected != null) {
        widget.onTimeSelected!(time);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Material(
          child: Container(
            padding: EdgeInsets.all(5),
            width: 204,
            height: 31,
            decoration: BoxDecoration(
              border: Border.all(width: 1, color: CustomColors.grey),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Row(
              children: [
                Material(
                  child: InkWell(
                    onTap: SelectedbeginTime,
                    child: Text(
                      _beginTime != null
                          ? StringTool.formatTimeOfDay(_beginTime!)
                          : '开始时间',
                    ),
                  ),
                ),
                Expanded(child: Text("-")),
                Material(
                  child: InkWell(
                    onTap: SelectedendTime,
                    child: Text(
                      _endTime != null
                          ? StringTool.formatTimeOfDay(_endTime!)
                          : '结束时间',
                    ),
                  ),
                ),
                Expanded(
                  child: Image.asset(
                    "assets/images/shijian.png",
                    width: 11,
                    height: 11,
                  ),
                ),

                const SizedBox(height: 10),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

class MyPage extends StatelessWidget {
  const MyPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    WidgetTools widgetTools = WidgetTools();
    return Scaffold(
      appBar: AppBar(title: const Text('结束时间选择示例')),
      body: Center(
        child: widgetTools.createEndTimePicker(
          context,
          onTimeSelected: (DateTime selectedTime) {
            print('选择的结束时间是: $selectedTime');
          },
        ),
      ),
    );
  }
}

class DatePickerWidget extends StatefulWidget {
  final BuildContext context;
  final Function(DateTime)? onTimeSelected;

  const DatePickerWidget({Key? key, required this.context, this.onTimeSelected})
    : super(key: key);

  @override
  _DatePickerWidgetState createState() => _DatePickerWidgetState();
}

@override
class _DatePickerWidgetState extends State<DatePickerWidget> {
  DateTime? _selectedTime, _beginTime, _endTime;

  Future<void> SelectedendTime() async {
    final DateTime? pickedDate = await showDatePicker(
      context: widget.context,
      initialDate: _selectedTime ?? DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );

    final DateTime newEndTime = DateTime(
      pickedDate!.year,
      pickedDate.month,
      pickedDate.day,
      pickedDate.hour,
      pickedDate.minute,
    );

    setState(() {
      _selectedTime = newEndTime;

      _endTime = newEndTime;
    });

    if (widget.onTimeSelected != null) {
      widget.onTimeSelected!(newEndTime);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Material(
          child: Container(
            padding: EdgeInsets.all(5),
            width: 204,
            height: 31,
            decoration: BoxDecoration(
              border: Border.all(width: 1, color: CustomColors.grey),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Row(
              children: [
                Material(
                  child: InkWell(
                    onTap: SelectedbeginTime,
                    child: Text(
                      _beginTime != null
                          ? StringTool.dateTimeToCustomString(
                            _beginTime!,
                            "yyyy-MM-dd",
                          )
                          : '开始日期',
                    ),
                  ),
                ),
                Expanded(child: Text(" -")),
                Material(
                  child: InkWell(
                    onTap: SelectedendTime,
                    child: Text(
                      _endTime != null
                          ? StringTool.dateTimeToCustomString(
                            _endTime!,
                            "yyyy-MM-dd",
                          )
                          : '结束日期',
                    ),
                  ),
                ),
                Expanded(
                  child: Image.asset(
                    "assets/images/shijian.png",
                    width: 11,
                    height: 11,
                  ),
                ),

                const SizedBox(height: 10),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Future<void> SelectedbeginTime() async {
    // 选择时间
    final DateTime? pickedDate = await showDatePicker(
      context: widget.context,
      initialDate: _selectedTime ?? DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );
    final DateTime newEndTime = DateTime(
      pickedDate!.year,
      pickedDate.month,
      pickedDate.day,
      pickedDate.hour,
      pickedDate.minute,
    );

    setState(() {
      _selectedTime = newEndTime;
      _beginTime = newEndTime;
    });

    if (widget.onTimeSelected != null) {
      widget.onTimeSelected!(newEndTime);
    }
  }
}

class Page extends StatelessWidget {
  const Page({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    WidgetTools widgetTools = WidgetTools();
    return Scaffold(
      appBar: AppBar(title: const Text('结束时间选择示例')),
      body: Center(
        child: widgetTools.createEndTimePicker(
          context,
          onTimeSelected: (DateTime selectedTime) {
            print('选择的结束时间是: $selectedTime');
          },
        ),
      ),
    );
  }
}
